# coding=utf-8
"""
作者：董新强 
创建时间：
描述：
"""
import hashlib
import json
from decimal import Decimal
from random import sample as randomsample


def get_len(obj):
    '''
    获取对象长度
    '''
    if not obj:
        return 0

    try:
        if isinstance(obj, (int, float, Decimal)):
            return len(str(obj).replace('.', '').replace('-', ''))
        return len(obj)
    except:
        return 0


def to_string(obj: object, failure_replace_value: object = None, strip_all_blank: object = False) -> object:
    '''
    将对象转换为字符串
    :param obj:带转换的类型
    :type obj:
    :param failure_replace_value:转换失败时代替的类型
    :type failure_replace_value: str
    :param strip_all_blank:是否移除所有空格 ,默认不移除
    :type strip_all_blank: bool
    :return:返回值
    :rtype: str
    '''
    try:
        if obj is None:
            return failure_replace_value

        if isinstance(obj, str):
            new_str = obj
        elif isinstance(obj, bytes):
            new_str = obj.decode(encoding='utf-8')
        elif isinstance(obj, (list, dict)):
            new_str = json.dumps(obj, ensure_ascii=False)
        else:
            new_str = str(obj)

        if strip_all_blank and new_str:
            return new_str.replace(' ', '')

        return new_str
    except:
        return failure_replace_value


def to_byte(str_or_byte):
    '''
    将str转换为bytes
    :param str_or_byte:
    :type str_or_byte:
    :return:
    :rtype:
    '''
    if not str_or_byte:
        return None
    if isinstance(str_or_byte, bytes):
        return str_or_byte
    if isinstance(str_or_byte, str):
        return str_or_byte.encode(encoding='utf-8')
    return None


def to_dict(str_or_byte, replace_obj=None):
    """
    将字符串或bytes转换为字典
    :param s:
    :type s:
    :return:
    :rtype:
    """
    if isinstance(str_or_byte, dict):
        return str_or_byte
    try:
        return json.loads(to_string(str_or_byte), encoding='utf-8')
    except:
        return replace_obj or {}


def to_int(str_num, failure_result=None):
    '''
    字符串转换为数字
    :param str_num:
    :type str_num:
    :return:
    :rtype:
    '''
    if isinstance(str_num, int):
        return str_num

    if str_num is None:
        return failure_result

    try:

        if isinstance(str_num, (float, Decimal)):
            return int(str_num)

        str_num = to_string(str_num)
        if not str_num:
            return failure_result

        return int(str(str_num))
    except Exception as e:
        return failure_result


def get_random_chars(length=12):
    assert isinstance(length, int)
    if length > 60:
        length = 60
    return ''.join(randomsample(r'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0987654321', length))


def to_sha256(content):
    return hashlib.sha256(to_string(content).encode("utf8")).hexdigest()
